package com.sky.anotion.validator;

import com.sky.anotion.ValidId;
import com.sky.enumeration.ValidIdType;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;

public class PositiveIdValidator implements ConstraintValidator<ValidId, Object> {

    private boolean required;
    private ValidIdType type;
    @Override
    public void initialize(ValidId constraintAnnotation) {
        this.required = constraintAnnotation.required();
        this.type = constraintAnnotation.value();
    }
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) return !required;

        if (value instanceof Collection<?>) {
            for (Object item : (Collection<?>) value) {
                if (!isValidSingle(item)) {
                    return false;
                }
            }
            return true;
        }

        return isValidSingle(value);
    }
    private boolean isValidSingle(Object value) {
        try {
            // 空字符串判断
            if (value instanceof String) {
                String str = ((String) value).trim();
                if (str.isEmpty()) {
                    return !required; // 为空则按 required 决定是否通过
                }
            }
            long id;
            switch (type) {
                case LONG:
                    if (value instanceof Long) {
                        id = (Long) value;
                    } else if (value instanceof Integer) {
                        id = ((Integer) value).longValue();
                    } else {
                        return false;
                    }
                    break;
                case INTEGER:
                    if (value instanceof Integer) {
                        id = ((Integer) value).longValue();
                    } else {
                        return false;
                    }
                    break;
                case STRING:
                    if (value instanceof String) {
                        id = Long.parseLong(((String) value).trim());
                    } else {
                        return false;
                    }
                    break;
                default:
                    return false;
            }
            return id >= 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
